package com.spider.admin.store.primary.mapper;

import com.spider.admin.store.primary.model.AccountPermissions;
import com.spider.admin.store.primary.model.AccountServicePerm;
import org.apache.ibatis.annotations.*;
import org.apache.ibatis.mapping.FetchType;

import java.util.List;

@Mapper
public interface AccountServicePermMapper {
    @Insert("INSERT INTO t_account_service_permissions(pid,account,service_id,v_pid)"
            + " VALUES(#{pid},#{account},#{serviceId},#{vPid})"
    )
    int saveAccountPerm(AccountServicePerm accountServicePerm);

    @Update("UPDATE t_account_service_permissions SET service_id=#{serviceId} WHERE pid=#{pid}")
    int updateAccountPerm(String serviceId, String pid);


    @Delete("delete from t_account_service_permissions where pid=#{pid}")
    int delAccountPerm(String pid);


    @Select("SELECT * FROM t_account_service_permissions WHERE account = #{account}")
    @Results(value = {
            @Result(column = "pid", property = "pid"),
            @Result(column = "account", property = "account"),
            @Result(column = "service_id", property = "serviceId"),
            @Result(column = "v_pid", property = "vPid"),
            @Result(property = "serviceInfo", column = "service_id",
                    one = @One(select = "com.duli123.hgg.db.primary.mapper.ServiceMapper.queryServiceById", fetchType = FetchType.EAGER)),
            @Result(property = "accountInfo", column = "account",
                    one = @One(select = "com.duli123.hgg.db.primary.mapper.AccountMapper.getAccountByName", fetchType = FetchType.EAGER))
    })
    List<AccountServicePerm> queryAccountPerm(String account);


    @Select({"SELECT tasp.v_pid, tai2.tenant_id, tsm.service_url ",
            "FROM t_account_service_permissions tasp,t_service_marks tsm,t_account_info tai2,t_application_info tai,t_cloud_info tci " ,
            "WHERE tai2.account_name=tasp.account " ,
            "AND tsm.pid=tasp.service_id " ,
            "AND tsm.app_id=tai.pid " ,
            "AND tai.cloud_id=tci.pid " ,
            "AND tsm.line_status='on'  " ,
            "AND tai2.archive_status='active' " ,
            "AND tai.app_status='active' " ,
            "AND tci.archive_status='active'"})
    @Results(value = {
            @Result(column = "v_pid", property = "vPid"),
            @Result(column = "tenant_id", property = "tenantId"),
            @Result(column = "service_url", property = "serviceUrl")
    })
    List<AccountPermissions> getAllActivePermissions();

    @Delete("delete from t_account_service_permissions where service_id=#{serviceId} And account=#{account}")
    int delAccountPermByAccountAndServiceId(String account, String serviceId);
}
